<template>
	<div>
		<img class="detailImage" :src="baseUrl + good.img">
		<el-form label-position="left" inline class="demo-table-expand">
			<el-form-item label="商品分类">
				<span>{{ good.category_name }}</span>
			</el-form-item>
			<el-form-item label="所属商家">
				<span>{{ good.user_name }}</span>
			</el-form-item>
			<el-form-item label="商品名称">
				<span>{{ good.name }}</span>
			</el-form-item>
			<el-form-item label="商品价格">
				<span>{{ good.price }}</span>
			</el-form-item>
			<el-form-item label="商品数量">
				<span>{{ good.num }}</span>
			</el-form-item>
		</el-form>
		<el-button type="primary" @click="addGoodCar(good.id)">添加购物车</el-button>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				baseUrl: "http://127.0.0.1:8000/",
				good_id: this.$route.query.good_id,
				good: "",
			}
		},
		created() {
			this.getDetail();
		},
		methods: {
			async getDetail() {
				let url = 'goodapi/operation/' + this.good_id + '/';
				console.log(url);
				let data = {
					"token": window.sessionStorage.getItem("token")
				}
				const {
					data: res
				} = await this.$http.get(url, {
					params: data
				});
				// console.log(res);
				this.good = res
			},
			async addGoodCar(id) {
				// console.log(id);
				if(this.good.num < 1){
					this.$message.error("添加购物车失败");
					return;
				}
				let url = 'goodcarapi/operation/?token=' + window.sessionStorage.getItem("token");
				
				let data = new FormData();
				data.append('u_id', window.sessionStorage.getItem("u_id"));
				data.append('good_id', id);
				// 默认添加购物车，数量为1
				data.append('buy_good_num', 1);
				const {data: res} = await this.$http.post(url, data);
				// console.log(res);
				if(res.id){
					this.$message.success("添加购物车成功");
					this.getDetail();
				}
				else{
					this.$message.error("添加购物车失败");
				}
			}
		}
	}
</script>

<style>
	.detailImage {
		width: 400px;
		height: 400px;
		/* display: block; */
		float: left;
	}

	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {
		width: 90px;
		color: #99a9bf;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}
</style>
